#include "nighteffect.h"
#include "vectorproperties.h"
#include "datatypedefine.h"
#include "transformableactor.h"
#include <osg\StateSet>
#include <osg\Node>
#include "layersmanager.h"
#include <osg\Program>
#include "environmentlayeractor.h"
#include "fogsettingactor.h"

static const char night_effect_vertex[] = 
"void main(void)\n"
"{\n"
	"gl_TexCoord[0]  = gl_MultiTexCoord0;\n"
	"gl_Position = ftransform();\n"
"}\n";

static const char night_effect_fragment[] = 
"uniform sampler2D tex;\n"
"void main (void)\n"
"{\n"
"vec4 v = vec4(0.004,0.1,0.135,1);\n"
"vec4 color1 = texture2D(tex,gl_TexCoord[0].st);\n"
"vec4 endcolor = mix(color1,v,0.7);\n"
"gl_FragColor = endcolor;\n"
"}\n";

namespace VrDataCore
{
	NightEffect::NightEffect()
	{
		setClassName("NightEffect");
	}

	NightEffect::~NightEffect()
	{}

	void NightEffect::buildPropertyMap()
	{
		EffectBase::buildPropertyMap();
	}

	void NightEffect::apply( CoreBase::ActorBase* actor)
	{
		if(!isIdle())
			return;
		dynamic_cast<TransformableActor*>(actor)->setUseDefaultStateSet(false);
		dynamic_cast<TransformableActor*>(actor)->useStateSet();
		osg::Node* node = actor->getDrawable()->getOSGNode();
		osg::StateSet* usestateset = node->getStateSet();
		osg::ref_ptr<osg::Shader> vertexShader = new osg::Shader( osg::Shader::VERTEX,night_effect_vertex);
		osg::ref_ptr<osg::Shader> fragmentShader = new osg::Shader( osg::Shader::FRAGMENT,night_effect_fragment);
		osg::ref_ptr<osg::Program> program = new osg::Program;
		program->setName("night effect program");
		program->addShader( vertexShader.get());
		program->addShader( fragmentShader.get());
		usestateset->setAttributeAndModes( program.get(), osg::StateAttribute::ON );
		CoreBase::ActorBase* fogactor = dynamic_cast<VrDataCore::EnvironmentLayerActor*>(
					VrDataCore::LayersManager::GetInstance().getEnvironmentLayer())->getFogSettingActor();
		FogSettingActor* f = dynamic_cast<FogSettingActor*>(fogactor);
		usestateset->setAttributeAndModes(f->getFog(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
		//osg::Uniform* param = new osg::Uniform("effectcolor",_materialEffect);
		//usestateset->addUniform( param );
		EffectBase::apply(actor);
	}

	void NightEffect::unApply( CoreBase::ActorBase* actor)
	{
		if(isIdle())
			return;
		dynamic_cast<TransformableActor*>(actor)->setToDefaultStateSet();
		EffectBase::unApply(actor);
	}

	osg::ref_ptr<CoreBase::ActorBase> NightEffect::clone()
	{
		osg::ref_ptr<CoreBase::ActorBase> clone = CoreBase::ActorBase::clone();
		return clone;
	}
}